<?php
namespace gnomephp;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;

class AppCMD{

	/**
	 * 
	 * Enter description here ...
	 * @var Symfony\Component\Console\Application
	 */
	static protected $cli;
	
	static public function main(){

		// Declare helpers
		\gnomephp\doctrine\Doctrine::load();

		$helpers = array(
			'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper(\gnomephp\doctrine\Doctrine::$em->getConnection()),
			'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper(\gnomephp\doctrine\Doctrine::$em)
		);

		$helperSet = new \Symfony\Component\Console\Helper\HelperSet($helpers);

		$helperSet = ($helperSet) ?: new \Symfony\Component\Console\Helper\HelperSet();

		self::$cli = new Application('Doctrine/GnomePHP Application Command Line Interface', \Doctrine\ORM\Version::VERSION);
        self::$cli->setCatchExceptions(true);
        self::$cli->setHelperSet($helperSet);
        
		\Doctrine\ORM\Tools\Console\ConsoleRunner::addCommands(self::$cli);
		self::addCommandsFromDir(GNOME_APP_PATH . DIRECTORY_SEPARATOR . 'command', GNOME_APP_NS . '\\' . 'command');
		self::addCommandsFromDir(GNOME_FW_PATH . DIRECTORY_SEPARATOR . 'appcommand', 'gnomephp\appcommand');
		
        self::$cli->run();
        
	}

	static protected function addCommandsFromDir($dir, $baseNS){

		$d = dir($dir);
		while (false !== ($entry = $d->read())) {
			if ($entry != '.' && $entry != '..' && substr($entry, -4) == '.php'){
				try{
					$obj = '\\'.$baseNS . '\\' . substr($entry, 0, -4);
					
					if (class_exists($obj)){
						$refClass = new \ReflectionClass($obj);
						
						// Check if its indeed a command.
						if ($refClass->isSubclassOf('Symfony\Component\Console\Command\Command')){
							self::$cli->add(new $obj());
						}
					}
				}catch(AutoLoaderException $e){
					
				}
			}
		}
		$d->close();
	}

}